package com.example.yang.yixin.Activity;

import android.Manifest;
import android.app.TimePickerDialog;
import android.content.ContentResolver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;

import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.NonNull;
import android.support.design.widget.Snackbar;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AlertDialog;
import android.support.v7.widget.DividerItemDecoration;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Base64;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.TimePicker;
import android.widget.Toast;

import com.android.volley.NetworkResponse;
import com.android.volley.ParseError;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.HttpHeaderParser;
import com.android.volley.toolbox.JsonObjectRequest;
import com.android.volley.toolbox.Volley;

import com.baidu.location.BDAbstractLocationListener;
import com.baidu.location.BDLocation;
import com.baidu.location.BDLocationListener;
import com.baidu.location.LocationClient;
import com.example.yang.yixin.Adapter.PersonAdapter;
import com.example.yang.yixin.R;

import com.example.yang.yixin.Socket.FaceMatch;
import com.example.yang.yixin.Socket.Signset;
import com.example.yang.yixin.Utils.Person_info;
import com.example.yang.yixin.Utils.T;
import com.example.yang.yixin.Views.InputView;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.ByteArrayOutputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.UnsupportedEncodingException;
import java.sql.Time;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class SignInActivity extends BaseActivity {
    private ImageView mIv_back;
    private Button btn_start;
    private List<Person_info> Person_info=new ArrayList<>();
    private RecyclerView mRecyclerView;
    private PersonAdapter madpater;
    private SmartRefreshLayout smartRefreshLayout;
    private TextView textView;
    private SharedPreferences pref;
    private SharedPreferences.Editor editor;
     static boolean flag=true;
    View view;
    LinearLayout re;
    int endtime=0;
    Calendar calendar=null;
    int hour=0;//获取小时
    int minutes=0;//获取分钟
    int allminutes=0;
    String identity= null;
    String bkpassword=null;//username的问题
    String username=null;
    String x=null;//从存储器获得距离的嘛？
    String y=null;
    private int TAKE_PHOTO=1;


    public LocationClient mlocationClient;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_sign_in);
        initView();

    }

    private void initView() {
        initNarvBar(true,"课堂签到",false);
        pref=getSharedPreferences("user",MODE_PRIVATE);
        btn_start=findViewById(R.id.button_start);
        textView=findViewById(R.id.number);
         mlocationClient=new LocationClient(getApplicationContext());

        //初始化

        calendar = Calendar.getInstance();
        hour=calendar.get(Calendar.HOUR_OF_DAY);
        minutes=calendar.get(Calendar.MINUTE);
        identity= pref.getString("identity",null);
        bkpassword=pref.getString("bkpassword",null);
        username=pref.getString("username",null);
        x=pref.getString("locationX",null);
        y=pref.getString("locationY",null);
        allminutes=60*hour+minutes;


        if(identity.equals("老师")){
            btn_start.setText("发起签到");
        }
        else{
            btn_start.setText("上课签到");
        }
        mRecyclerView=findViewById(R.id.iv_recycler);
        LinearLayoutManager layoutManager=new LinearLayoutManager(this);
        mRecyclerView.setLayoutManager(layoutManager);
        mRecyclerView.addItemDecoration(new DividerItemDecoration(this,DividerItemDecoration.VERTICAL));
        smartRefreshLayout=findViewById(R.id.smart_refresh);
        mIv_back=findViewById(R.id.iv_back);
        mIv_back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent=new Intent(SignInActivity.this,PersonActivity.class);
                startActivity(intent);
            }
        });
        mlocationClient.registerLocationListener((BDAbstractLocationListener) new MyLocationListener());
        List<String> permissionList=new ArrayList<>();
        if(ContextCompat.checkSelfPermission(SignInActivity.this,Manifest.permission.ACCESS_FINE_LOCATION)!=PackageManager.PERMISSION_GRANTED){
            permissionList.add(Manifest.permission.ACCESS_FINE_LOCATION);
        }
        if(ContextCompat.checkSelfPermission(SignInActivity.this,Manifest.permission.READ_PHONE_STATE)!=PackageManager.PERMISSION_GRANTED){
            permissionList.add(Manifest.permission.READ_PHONE_STATE);
        }
        if(ContextCompat.checkSelfPermission(SignInActivity.this,Manifest.permission.WRITE_EXTERNAL_STORAGE)!=PackageManager.PERMISSION_GRANTED){
            permissionList.add(Manifest.permission.WRITE_EXTERNAL_STORAGE);
        }
        if(!permissionList.isEmpty()){
            String [] permissions=permissionList.toArray(new String[permissionList.size()]);
            ActivityCompat.requestPermissions(SignInActivity.this,permissions,1);
        }else{
            requestLocation();
        }
        btn_start.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                if(identity.equals("老师")) {
                    if(btn_start.getText().equals("结束签到")){
                        Signset.SetSign(bkpassword, "close", getApplicationContext(), x, y, 0,0, getWindow().getDecorView());//设置签到状态是0,同时将所有学生的签到状态变为0;
                        flag = true;
                        btn_start.setText("开始签到");
                    }else {
                        Edit_End_time();
                    }
                }
                else{
                            /*
                            在这里调用摄像机，首先完成人脸识别，人脸识别成功则进行距离判断
                             */
                            if(pref.getBoolean("INPUT_OR_NOT",false)) {
                                Intent mIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
                                startActivityForResult(mIntent, TAKE_PHOTO);//启动摄像机，然后写获得的图片怎么解决
                            }else{
                                Snackbar.make(v,"请先完成人脸设置！",Snackbar.LENGTH_LONG).setAction("立即设置", new View.OnClickListener() {
                                    @Override
                                    public void onClick(View v) {
                                        Intent intent=new Intent();
                                        intent.setClass(SignInActivity.this,FaceActivity.class);
                                        startActivity(intent);
                                    }
                                }).show();
                            }




                }
            }
        });
        getServerData();
        smartRefreshLayout.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(@NonNull RefreshLayout refreshLayout) {
                refreshLayout.finishRefresh(2000);
                Person_info.clear();
                getServerData();
            }
        });


    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {  //回传值接受成功

            if (requestCode == TAKE_PHOTO) {    //拍照取图

                Bundle bundle = data.getExtras();
                //获取data数据集合
                Bitmap bitmap = (Bitmap) bundle.get("data");//获得data数据
                saveBitmapToSDCard(bitmap, "facepic");
                ByteArrayOutputStream baos = new ByteArrayOutputStream();
                bitmap.compress(Bitmap.CompressFormat.JPEG, 50, baos);
                String imageBase64 = new String(Base64.encodeToString(baos.toByteArray(), Base64.DEFAULT));
                editor.putString("pic", imageBase64);
                editor.commit();
                Toast.makeText(getApplicationContext(),"在线识别大约需要5s，请等待...",Toast.LENGTH_LONG).show();
                //启动子线程去识别人脸
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        String result=FaceMatch.match();
                        Message msg=handler.obtainMessage();
                        JsonObject jObject = new JsonParser().parse(result).getAsJsonObject();
                        JsonElement jsonElement = jObject.get("result");
                        float score = 0;

                        if(!jsonElement.isJsonNull()){    //人脸对比出错的话，这里是空的
                            score = jsonElement.getAsJsonObject().get("score").getAsFloat();
                        }
                        if(score>=80.0){
                            msg.what=0;
                            handler.sendMessage(msg);
                        }else{
                            msg.what=1;
                            handler.sendMessage(msg);
                        }
                        Log.d("score", score+"");//取出来了
                    }
                    }).start();

                Log.i("TAG", "拍照回传bitmap：" + bitmap);

            }
        }


    }
    Handler handler = new Handler()
    {
        public void handleMessage(Message msg)
        {
            switch(msg.what)
            {
                case 0:
                     if(flag) {
                               boolean Success_or_Defeat= Signset.GetSign(bkpassword, username, getApplicationContext(), x, y,allminutes,getWindow().getDecorView());
                               if(Success_or_Defeat){
                                   flag=false;
                                   btn_start.setText("下课签到");
                               }
                            }
                            else{
                                Calendar calendar=Calendar.getInstance();
                                int h=calendar.get(Calendar.HOUR_OF_DAY);
                                int m=calendar.get(Calendar.MINUTE);
                                endtime=h*60+m;
                                new MyLocationListener();//结束签到时要刷新位置
                                String x=pref.getString("locationX",null);
                                String y=pref.getString("locationY",null);

                                if(true) {
                                    Signset.GetEndfSign(bkpassword, username, getApplicationContext(), x, y, endtime,getWindow().getDecorView());
                                    Toast.makeText(getApplicationContext(),"bkpassword:"+bkpassword+" username:"+username,Toast.LENGTH_LONG).show();
                                }
                                flag=true;
                                btn_start.setText("上课签到");
                            }
                    break;
                case 1:
                    Snackbar.make(getWindow().getDecorView(),"识别失败,相似度低于80",Snackbar.LENGTH_LONG).setAction("我知道了", new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                        }
                    }).show();
                    break;

            }

        }
    };
    public void saveBitmapToSDCard(Bitmap bitmap, String imagename)
    {
        FileOutputStream fos = null;
        if (Build.VERSION.SDK_INT >= 23) {
            int REQUEST_CODE_CONTACT = 101;
            String[] permissions = {Manifest.permission.WRITE_EXTERNAL_STORAGE};
            //验证是否许可权限
            for (String str : permissions) {
                if (this.checkSelfPermission(str) != PackageManager.PERMISSION_GRANTED) {
                    //申请权限
                    this.requestPermissions(permissions, REQUEST_CODE_CONTACT);
                    return;
                }
            }
        }

        try {
            fos = new FileOutputStream("/sdcard/Pictures/" +imagename+ ".jpg");//把照片存在Images文件夹中
            if (fos != null) {
                bitmap.compress(Bitmap.CompressFormat.JPEG, 90, fos);
                fos.close();
            }
        } catch (Exception e) {
            e.printStackTrace();
            Toast.makeText(getApplicationContext(),e.getMessage(),Toast.LENGTH_LONG).show();
        }
    }
    private void Edit_End_time() {
        re = (LinearLayout) getLayoutInflater().inflate(R.layout.time, null);
        AlertDialog.Builder dialog = new AlertDialog.Builder(SignInActivity.this);
        dialog.setTitle("课程时长");
        dialog.setView(re);
        dialog.setNeutralButton("确定", new LoginClick());
        dialog.setPositiveButton("取消", new CencleClick());
        dialog.create();
        dialog.show();
    }

    private class CencleClick implements DialogInterface.OnClickListener {
        @Override
        public void onClick(DialogInterface dialog, int which) {
            dialog.cancel();
        }
    }

    private class LoginClick implements DialogInterface.OnClickListener {

        public void onClick(DialogInterface dialog, int which) {
            InputView editText1=(InputView)re.findViewById(R.id.input_time) ;
            Toast.makeText(getApplicationContext(),allminutes+"",Toast.LENGTH_LONG).show();
            int endtime=Integer.parseInt(editText1.getInputStr())+allminutes;

           if(flag) {

                Signset.SetSign(bkpassword,"open",getApplicationContext(),x,y,allminutes,endtime,getWindow().getDecorView());//设置签到状态是1,从course表里面去找bkpassword并把状态设置为一;
                flag=false;
                btn_start.setText("结束签到");
            }

        }
    }
    private void requestLocation() {
        mlocationClient.start();
    }
    public void onRequestPermissionsResult(int requestCode,String[] permissions, int[] grantResults) {
        switch (requestCode){
            case 1:
                if(grantResults.length>0){
                    for(int result:grantResults){
                        if(result!=PackageManager.PERMISSION_GRANTED){

                            Snackbar.make(view,"请授权后重新尝试！",Snackbar.LENGTH_SHORT).setAction("取消", new View.OnClickListener() {
                                @Override
                                public void onClick(View v) {

                                }
                            }).show();
                            finish();
                            return;
                        }
                    }
                    requestLocation();
                }else{
                    Toast.makeText(getApplicationContext(),"发生未知错误",Toast.LENGTH_SHORT).show();
                    finish();
                }
                break;
            default:
        }

    }

    private class MyLocationListener extends BDAbstractLocationListener implements BDLocationListener {
        @Override
        public void onReceiveLocation(final BDLocation bdLocation) {
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    editor=pref.edit();
                    double locationX=bdLocation.getLatitude();
                    double locationY=bdLocation.getLongitude();
                    editor.putString("locationX",locationX+"");
                    editor.putString("locationY",locationY+"");
                    editor.apply();
                }
            });
        }
    }


    public  void getServerData() {
        String jsonurl =  "http://47.106.141.161/MyFirstAndroidApp/SelectpersonServlet?bkpassword="+getIntent().getStringExtra("bkpassword")+"&flag=sign";
        RequestQueue mQueue = Volley.newRequestQueue(this);
        JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(jsonurl, null, new Response.Listener<JSONObject>() {
            @Override
            public void onResponse(JSONObject response) {
                try {

                    String name;
                    String cname;
                    String username;
                    int size=Integer.parseInt(response.getString("size")) ;
                    for (int i = 0; i < size; i++) {
                        /*
                        这个地方要修改
                         */
                        username = new String(response.getString("username"+i));
                        name = new String(response.getString("name"+i));
                        cname = new String(response.getString("classname"+i));
                        Person_info a = new Person_info(username, name,cname);
                        Person_info.add(a);

                    }

                } catch (JSONException e) {
                    String name;
                    String cname;
                    String username;
                    name="全部都签到啦！";
                    cname="";
                    username="";
                    Person_info a =  new Person_info(username, name,cname);;
                    Person_info.add(a);

                }
                String number=Integer.toString(Person_info.size());
                textView.setText(number);
                madpater=new PersonAdapter(Person_info);

                mRecyclerView.setAdapter(madpater);
            }
        },
                new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError volleyError) {
                        Log.e("TAG错误", volleyError.getMessage(), volleyError);
                    }
                }) {
            protected Response<JSONObject> paraeNetworkResponse(NetworkResponse response) {
                try {
                    JSONObject jsonObject = new JSONObject(new String(response.data, "utf-8"));
                    return Response.success(jsonObject, HttpHeaderParser.parseCacheHeaders(response));
                }catch (JSONException je) {
                    return Response.error(new ParseError(je));
                } catch (UnsupportedEncodingException e) {
                    return Response.error(new ParseError(e));
                }

            }
        };


        mQueue.add(jsonObjectRequest);

    }

    @Override
    protected void onRestart() {
        super.onRestart();
    }
}
